package com.leyou.cart.service;

import com.leyou.cart.domain.Cart;
import com.leyou.common.auth.domain.UserHolder;
import com.leyou.common.exception.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String CART_PRE="CART:PRE:";

    public void addCart(Cart cart) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //获取当前用户在reids中的hashKey
        String hashKey = CART_PRE + userId;
        //获取redis中购物车
        BoundHashOperations<String, String, String> hashMap = redisTemplate.boundHashOps(hashKey);
        //判断购物车中是否有购物车对象
        Boolean hasCart = hashMap.hasKey(cart.getSkuId().toString());
        if (hasCart) {
            //得到原来购物车中对应skuId的cart
            String oldCartStr = hashMap.get(cart.getSkuId().toString());
            //把字符串类型的购物车对象转换为对象类型
            Cart oldCartObj = JsonUtils.toBean(oldCartStr, Cart.class);
            //把老的购物车的数量合并到新的购物对象中
            cart.setNum(cart.getNum()+oldCartObj.getNum());
        }
        //保存购物车
        hashMap.put(cart.getSkuId().toString(),JsonUtils.toString(cart));
    }

    public List<Cart> findCartList() {
        Long userId = UserHolder.getUserId();
        String hashKey = CART_PRE + userId;
        if (!redisTemplate.hasKey(hashKey)) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //得到当前用户的购物hash
        BoundHashOperations<String, String, String> hashMap = redisTemplate.boundHashOps(hashKey);
        //遍历购物车map获取所有的value
        Map<String, String> entries = hashMap.entries();
        List<Cart> cartList = entries.values().stream().map(cart -> JsonUtils.toBean(cart, Cart.class)).collect(Collectors.toList());
        return cartList;
    }

    public void addLocalCartToRedis(List<Cart> carts) {
        for (Cart cart : carts) {
            addCart(cart);
        }
    }
}
